<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-wms__order}">
      <div class="ba-operate-form">
        <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="80px">
          <el-row :gutter="20">
            <el-col :md="5" :sm="5">
              <el-form-item label="砂芯图号" prop="spuNo">
                <el-select v-model="dataForm.spuNo" filterable placeholder="请选择砂芯">
                  <el-option v-for="item in options" :key="item.spuId" :label="item.spuNo" :value="item.spuNo">
                    <span style="float: left">{{ item.spuNo }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.lotNo }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <el-form-item label="批次" prop="lotNo">
                <el-input v-model="dataForm.lotNo" @keyup.enter.native="getStockBySpu" placeholder="请输入批次"
                  maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <el-button-group>
                <el-button @click="getStockBySpu()" type="success">{{
                  $t("queryStock")
                }}</el-button>
              </el-button-group>
            </el-col>
            <el-col :md="2" :sm="2">
              <el-tag>1号堆垛机</el-tag>
            </el-col>
            <el-col :md="5" :sm="5">
              <el-radio-group v-model="radio1" @change="stateChange('TC01')">
                <el-radio :label="0">禁止入</el-radio>
                <el-radio :label="1">不限制</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :md="5" :sm="5">
              <el-form-item label="库存数量">
                <el-input v-model="stockQnty"></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <el-form-item label="可用数量">
                <el-input v-model="usableQnty"></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <el-form-item> </el-form-item>
            </el-col>
            <el-col :md="2" :sm="2">
              <el-tag>2号堆垛机</el-tag>
            </el-col>
            <el-col :md="5" :sm="5">
              <el-radio-group v-model="radio2" @change="stateChange('TC02')">
                <el-radio :label="0">禁止入</el-radio>
                <el-radio :label="1">不限制</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :md="5" :sm="5">
              <el-form-item label="终点位置" prop="stationNo">
                <el-select v-model="dataForm.stationNo" filterable placeholder="请选择站台">
                  <el-option v-for="item in stationOptions" :key="item.stationId" :label="item.stationNo"
                    :value="item.stationNo">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <el-form-item label="需求数量" prop="amount">
                <el-input-number v-model="dataForm.amount" :min="2" :max="24" :step="2"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <el-button v-if="$hasPermission('wms:order:save')" @click="dataFormSubmitHandle()" type="primary">{{
                $t("releaseTask") }}</el-button>

              <el-button v-if="$hasPermission('wms:order:hang-up')" @click="orderHangUp()" type="warning">{{
                $t("hangUp") }}</el-button>
            </el-col>
            <el-col :md="2" :sm="2">
              <el-tag>3号堆垛机</el-tag>
            </el-col>
            <el-col :md="5" :sm="5">
              <el-radio-group v-model="radio3" @change="stateChange('TC03')">
                <el-radio :label="0">禁止入</el-radio>
                <el-radio :label="1">不限制</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 主表内容 -->
      <el-table class="orderTable" v-loading="dataListLoading" :row-key="getRowKey" :data="dataList"
        :expand-row-keys="expands" border ref="Table" @select="selectChangeHandle" style="width: 100%"
        @expand-change="rowExpand">
        <el-table-column type="expand">
          <!-- 明细内容 -->
          <el-table :data="detailList" border style="width: 100%">
            <el-table-column prop="detailId" label="明细id" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="childHandle(scope.row)">{{
                  scope.row.detailId
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="detailSt" label="明细状态" align="center" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.detailSt === 0">初始</el-tag>
                <el-tag v-else-if="scope.row.detailSt === 1">出库中</el-tag>
                <el-tag v-else-if="scope.row.detailSt === 2">出库完成</el-tag>
                <el-tag v-else-if="scope.row.detailSt === 3" type="success">完成确认</el-tag>
                <el-tag v-else-if="scope.row.detailSt === 9" type="warning">废弃</el-tag>
                <el-tag v-else type="danger">未知状态</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="contNo" label="托盘条码" align="center" min-width="220"
              show-overflow-tooltip></el-table-column>
            <el-table-column prop="spuNo" label="砂芯图号" align="center" min-width="110"></el-table-column>
            <el-table-column prop="lotNo" label="批次" align="center"></el-table-column>
            <el-table-column prop="planQnty" label="计划量" align="center"></el-table-column>
            <el-table-column prop="bindQnty" label="绑定量" align="center"></el-table-column>
            <el-table-column prop="actlQnty" label="实发量" align="center"></el-table-column>

            <el-table-column prop="creatorName" label="创建用户" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createDate" label="创建日期" align="center" min-width="155"></el-table-column>
            <el-table-column prop="updaterName" label="更新用户" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="updateDate" label="更新日期" align="center" min-width="155"></el-table-column>
            <el-table-column prop="comments" label="备注" align="center" show-overflow-tooltip></el-table-column>
          </el-table>
        </el-table-column>
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="orderId" label="id" header-align="center" align="center" sortable></el-table-column>
        <el-table-column prop="orderSt" label="主单状态" header-align="center" align="center" min-width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.orderSt === 0">初始</el-tag>
            <el-tag v-else-if="scope.row.orderSt === 1">出库中</el-tag>
            <el-tag v-else-if="scope.row.orderSt === 2" type="success">出库完成</el-tag>
            <el-tag v-else-if="scope.row.orderSt === 9" type="warning">废弃</el-tag>
            <el-tag v-else type="danger">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="单据编号" header-align="center" align="center" min-width="145" sortable>
        </el-table-column>
        <el-table-column prop="spuNo" label="砂芯图号" header-align="center" align="center" min-width="135">
        </el-table-column>
        <el-table-column prop="lotNo" label="批次" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="amount" label="需求数量" header-align="center" align="center"></el-table-column>

        <el-table-column prop="stationNo" label="终点位置" header-align="center" align="center" min-width="120">
        </el-table-column>
        <el-table-column prop="creatorName" label="创建用户" header-align="center" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="createDate" label="创建日期" header-align="center" align="center" min-width="155" sortable>
        </el-table-column>
        <el-table-column prop="updaterName" label="更新用户" header-align="center" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="updateDate" label="更新日期" header-align="center" align="center" min-width="155" sortable>
        </el-table-column>
        <el-table-column prop="comments" label="备注" header-align="center" align="center"></el-table-column>
      </el-table>
      <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle">
      </el-pagination>
    </div>
  </el-card>
</template>

<script>
import mixinViewModule from "@/mixins/view-module";
import debounce from "lodash/debounce";
import { addDynamicRoute } from "@/router";
export default {
  mixins: [mixinViewModule],
  data() {
    return {
      radio1: 1,
      radio2: 1,
      radio3: 1,
      mixinViewModuleOptions: {
        getDataListURL: "/wms/order/page",
        getDataListIsPage: true,
        exportURL: "/wms/order/export",
        deleteURL: "/wms/order",
        deleteIsBatch: true,
        orderKey: "orderId", // 自动配货时由orderId进行标记操作
      },
      dataForm: {
        orderId: "",
        orderType: "出库下架",
        spuNo: "",
        lotNo: "",
        amount: "",
        stationNo: "",
      },
      stateForm: {
        id: 1,
        dvcNo: '',
        status: 0
      },
      stockQnty: "0",
      usableQnty: "0",
      options: [],
      stationOptions: [],
      stationType: "CTN",
      dictType: "order_status",
      routeTitle: "关联任务-出库",
      getRowKey(row) {
        return row.orderId;
      },
      expands: [],
      detailList: null,
    };
  },
  created() {
    this.getSpuInfo();
    this.getStationInfo();
    this.getDvcStateInfo();
  },
  computed: {
    dataRule() {
      return {
        spuNo: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        lotNo: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        amount: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        stationNo: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  methods: {
    //0.重置搜索框
    getReset() {
      this.dataForm = this.$options.data().dataForm;
      this.dateRange = this.$options.data().dateRange;
    },
    stateChange(dvcNo) {
      console.log(dvcNo);
      this.stateForm.dvcNo = dvcNo;
      if (dvcNo == 'TC01') {
        this.stateForm.id = 1;
        this.stateForm.status = this.radio1;
      } else if (dvcNo = 'TC02') {
        this.stateForm.id = 2;
        this.stateForm.status = this.radio2;
      } else {
        this.stateForm.id = 3;
        this.stateForm.status = this.radio3;
      }
      this.$http[!this.stateForm.id ? "post" : "put"](
        "/wms/dvc-state/",
        this.stateForm
      ).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.$message({
          message: this.$t("prompt.success"),
          type: "success",
          duration: 500,
          onClose: () => {
            
          },
        });
      })
        .catch(() => { });
    },
    //0.获取砂芯图号
    getSpuInfo() {
      this.$http
        .get(`/wms/spu-info/list`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.options = res.data;
        })
        .catch(() => { });
    },
    //2.获取站台信息
    getStationInfo() {
      this.$http
        .get(`/wms/station/list`, {
          params: {
            stationType: this.stationType,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.stationOptions = res.data.filter((item, index) => {
            return item.status == 0;
          });
        })
        .catch(() => { });
    },
    getDvcStateInfo() {
      this.$http
        .get(`/wms/dvc-state/list`, {
          params: {
            dvcNo: 'TC',
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          res.data.forEach(item => {
            if (item.dvcNo === 'TC01') {
              this.radio1 = parseInt(item.status)
            }
            if (item.dvcNo === 'TC02') {
              this.radio2 = parseInt(item.status)
            }
            if (item.dvcNo === 'TC03') {
              this.radio3 = parseInt(item.status)
            }
          })
        })
        .catch(() => { });
    },
    //1.明细展开
    rowExpand(row, expandedRows) {
      this.expands = [];
      if (expandedRows.length > 0) {
        row ? this.expands.push(row.orderId) : "";
        this.orderNo = row.orderNo;
        this.detailList = row.orderDetailList;
      }
    },
    // 2.单选(确认出库单据id)
    selectChangeHandle(selection, row) {
      this.dataForm.orderId = ""; //每次单选都重置id

      if (selection.length > 1) {
        this.$refs.Table.clearSelection();
        this.$refs.Table.toggleRowSelection(row);
      }
      if (selection.length != 0) {
        //只有当真正选中了目标主单才获取id
        this.dataForm.orderId = row.orderId;
      }
    },
    // 3.任务跳转
    childHandle(row) {
      // 路由参数
      const routeParams = {
        routeName: `${this.$route.name}__${row.detailId}`,
        title: `${this.routeTitle} - ${row.detailId}`,
        path: "wms/detail-task",
        params: {
          mtNo: this.orderNo,
          dtId: row.detailId,
        },
      };
      // 动态路由
      addDynamicRoute(routeParams, this.$router);
    },
    //4.获取砂芯库存数量
    getStockBySpu() {
      this.$http
        .get(`/wms/stock/usage`, {
          params: {
            spuNo: this.dataForm.spuNo,
            lotNo: this.dataForm.lotNo,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.usableQnty = res.data.usableQnty;
          this.stockQnty = res.data.stockQnty;
        })
        .catch(() => { });
    },
    // 3.表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.dataForm.orderId = "";

        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.$http["post"]("/wms/order/", this.dataForm)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.getStockBySpu();
                  this.query();
                },
              });
            })
            .catch((errMsg) => {
              return this.$message.error("通讯异常!");
            });
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
    //出库单挂起
    orderHangUp() {
      if (!this.dataForm.orderId) {
        return this.$message({
          message: this.$t("prompt.hangUp"),
          type: "warning",
          duration: 1000,
        });
      }

      this.$confirm(
        this.$t("prompt.info", { handle: this.$t("hangUp") }),
        this.$t("prompt.title"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(() => {
          this.$http
            .put(`/wms/order/${this.dataForm.orderId}`)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: res.msg,
                type: "success",
                duration: 500,
                onClose: () => {
                  this.query();
                },
              });
            })
            .catch(() => { });
        })
        .catch(() => { });
    },
  },
};
</script>
<style>
/* 隐藏表头的全选框 */
.orderTable thead .el-table-column--selection .cell {
  display: none;
}

.el-row {
  margin-bottom: 0px;
}

.right-handle-group {
  float: right;
}
</style>